package com.itcoon.cloud.framework.transform.assemble.validator;


import com.itcoon.cloud.framework.transform.constants.ComponentOrderConstants;
import com.itcoon.cloud.framework.transform.exception.AssembleException;

import java.lang.reflect.Type;
import java.util.Arrays;

/**
 * @author Miaoxia Yu
 * @date 2020-11-05
 */
public class AnonymousValidator implements SourceValidator{

    @Override
    public boolean support(Object source) {
        return source.getClass().isAnonymousClass();
    }

    @Override
    public void validate(Object source, Class<?> originClass) {
        Class<?> sourceType = source.getClass();
        Class<?> superClass = sourceType.getSuperclass();
        if(Object.class.equals(superClass)){
            Type[] genericInterfaces = sourceType.getGenericInterfaces();
            long count = Arrays.stream(genericInterfaces).filter(interClazz->((Class)interClazz).isAssignableFrom(originClass)).count();
            if(count == 0){
                throw new AssembleException(String.format("Illegal Source anonymous,it required sourceClass '%s',but not found", originClass));
            }
        }else{
            if(!superClass.isAssignableFrom(originClass)){
                throw new AssembleException(String.format("Illegal Source anonymous,it required sourceClass '%s',but not found", originClass));
            }
        }
    }

    @Override
    public int getOrder() {
        return ComponentOrderConstants.ASSEMBLE_SOURCE_VALIDATOR_MIN + 10;
    }
}
